package com.example.navigationdemo.part1

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.fragment.app.Fragment
import androidx.navigation.findNavController
import androidx.navigation.fragment.NavHostFragment
import com.example.navigationdemo.R
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        //这里需要判断当前fragment是不是没变，没变就不跳转，因为navigation不运行目标是自己
        tv_to_fragment1.setOnClickListener {
            if (getFragment(NavigationFragment1::class.java) == null) {
                findNavController(R.id.fragment_container_view).navigate(
                    R.id.to_fragment1
                )
            }
        }
        tv_to_fragment2.setOnClickListener {
            if (getFragment(NavigationFragment2::class.java) == null) {
                findNavController(R.id.fragment_container_view).navigate(
                    R.id.to_fragment2
                )
            }
        }

    }

    @Suppress("UNCHECKED_CAST")
    fun <F : Fragment> AppCompatActivity.getFragment(fragmentClass: Class<F>): F? {
        val navHostFragment = this.supportFragmentManager.fragments.first() as NavHostFragment

        navHostFragment.childFragmentManager.fragments.forEach {
            if (fragmentClass.isAssignableFrom(it.javaClass)) {
                return it as F
            }
        }

        return null
    }
}